package com.macro.mall.tiny.filter;

import com.macro.mall.tiny.common.utils.JwtUtil;
import com.macro.mall.tiny.common.utils.RedisCache;
import com.macro.mall.tiny.domain.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        String token=request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        // 去除 "Bearer " 前缀（注意Bearer后有一个空格，共7个字符）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7); // 从索引7开始截取，得到纯JWT令牌
        }else{
            throw new RuntimeException("token异常");
        }

        //解析userId
        String userId;
        try{
            Claims claims= JwtUtil.parseJWT(token);
            userId=claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        //从redis中获取用户信息
        String userKey="Userlogin"+userId;
        LoginUser loginUser=redisCache.getCacheObject(userKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //放行
        filterChain.doFilter(request,response);
    }
}



